import { createStore, applyMiddleware, compose } from 'redux'
import { persistStore, persistReducer, Storage } from 'redux-persist'
import Taro from '@tarojs/taro'
import thunkMiddleware from 'redux-thunk'
import rootReducer from '../reducers'

const composeEnhancers =
  typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
      })
    : compose

const middlewares = [thunkMiddleware]

if (
  process.env.NODE_ENV === 'development' &&
  process.env.TARO_ENV !== 'quickapp'
) {
  // middlewares.push(require('redux-logger').createLogger())
}

const enhancer = composeEnhancers(
  applyMiddleware(...middlewares)
  // other store enhancers if any
)

const storage: Storage = {
  getItem(key: string) {
    return new Promise(function(resolve) {
      resolve(Taro.getStorageSync(key))
    })
  },
  setItem(key: string, data: any) {
    return Taro.setStorage({ key, data })
  },
  removeItem(key: string) {
    return Taro.removeStorage({ key })
  },
}

const persistConfig = {
  key: 'root',
  storage,
  whitelist: ['user', 'counter'],
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = createStore(persistedReducer, enhancer)
export const persistor = persistStore(store)
